package io.esirong.net.retrofit;

import io.esirong.net.BaseResponse;
import io.esirong.net.RespHandler;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * (简单的网络请求回调处理）BaseCallBack 实现{@link Callback}
 * <p>
 * 会自动处理HttpStatusCode != 200的提示
 * 会自动处理响应中常见的异常（Exception)
 * 建议根据实际情况选择使用
 *
 * @author esirong
 * @see RespHandler RespHandler
 * <p>
 * Created by 黄嵘才 on 2017/7/8.
 */

public abstract class BaseCallBack<T> implements Callback<BaseResponse<T>> {

    @Override
    public void onResponse(Call<BaseResponse<T>> call, Response<BaseResponse<T>> response) {
        if (response.isSuccessful()) {
            //1 接口请求成功，对返回的数据进行处理
            onResponseSuccessful(call, response);
        } else {
            //2 对后台返回的请求错误，进行处理
            //根据HttpCode处理
            onResponseFailure(call, response);
        }
        onComplete();
    }

    @Override
    public void onFailure(Call<BaseResponse<T>> call, Throwable throwable) {
        throwable.printStackTrace();
        onFail(call, throwable);
        onComplete();
    }

    /**
     * 业务操作正常回调
     *
     * @param call {@link Call}
     * @param body 回调的对象 继承<extends>{@link BaseResponse}
     */
    protected abstract void onSuccess(Call<BaseResponse<T>> call, BaseResponse<T> body);

    /**
     * 子类可以覆写它，然后完成这个错误的处理
     */
    protected void onFail(Call<BaseResponse<T>> call, Throwable throwable) {
        RespHandler.instance().handResponseError(throwable);
    }

    protected void onComplete() {
        //完成
    }

    private BaseResponse<T> onResponseSuccessful(Call<BaseResponse<T>> call, Response<BaseResponse<T>> response) {
        BaseResponse<T> body = response.body();
        boolean isSuccess = false;
        if (body != null) {
            if (RespHandler.isOk(body)) {
                isSuccess = true;
            }
        }
        if (isSuccess) {
            onSuccess(call, body);
        } else {
            //处理业务码
            onSuccess(call, body);
        }
        return body;
    }

    private void onResponseFailure(Call<BaseResponse<T>> call, Response<BaseResponse<T>> response) {
        RespHandler.instance().handStatusCode(response.code());
    }
}
